<template>
  <el-card>
    <div slot="header">
      <h3>批量新增-基本信息</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品
        </el-button>
        <el-button
          v-if="baseTableData.length > 0"
          type="text"
          size="large"
          @click="handleExportData"
          :loading="exportLoading"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/batch/prepare/basicinfo/saveBasicInfoToPage`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <el-button
          v-if="baseTableData.length > 0"
          type="text"
          size="large"
          @click="handleSubmitData"
          :loading="submitLoading"
          >提交</el-button
        >
      </el-row>
      <el-row>
        <general-render-table
          :loading="spuTableLoading"
          :data-source="baseTableData"
          :columns="basicTableColumns"
          @handleCancelSelect="handleCancelSelect"
        />
      </el-row>
    </div>
    <!-- 关联商品-SPU维度弹框 -->
    <spu-associated-dialog
      ref="spuModal"
      :columns="associatedGoodsTableColumns"
      :requestApi="requestApi"
      :requestParams="requestParams"
      :distinctParams="distinctParams"
      :isAccurateSearchClassify="true"
      @getRowList="getAssociatedGoodsAction"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
/* constants */
import { basicinfoRequiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import { ADD_BASE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { getAttributeTypeFn } from '@/pages/commodity/modules/utils';
import { getDealBaseDataToApiFn } from '@/pages/commodity/modules/utils/basicInfoRequireUtils';
export default {
  mixins: [spuDimensionMixins],
  components: {
    SpuAssociatedDialog,
    GeneralRenderTable
  },
  data () {
    return {
      exportLoading: false, // 导出按钮loading
      submitLoading: false, // 提交按钮loading
      requestApi: {
        url: ['/sysback/batch/prepare/basicinfo/getProductList'], // 关联商品查询接口
        type: 'post'
      },
      requestParams: basicinfoRequiredParams.requestParams, // 关联商品查询接口所需入参
      distinctParams: basicinfoRequiredParams.distinctParams, // 关联商品查询接口区别未关联和已关联的入参
      associatedGoodsTableColumns: [
        // 关联商品弹框表格columns
        { type: 'selection', width: 60, align: 'center' },
        { title: '商品名称', key: 'productNameFinal', width: 150 },
        { title: 'SPU编码', key: 'spuNo', width: 180 },
        { title: '商品分类', key: 'categoryPath', width: 180 },
        { title: '管理区域', key: 'manageAreaName', width: 150 },
        { title: '规格参数', key: 'saleAttrInfo', width: 150 },
        { title: '品牌', key: 'brandName', width: 150 },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      linshiBaseTableData: [], // 列表的数据源
      baseTableData: [], // 列表的数据源
      basicTableColumns: [], // 表格columns
      spuTableLoading: false, // 表格数据加载loading
      initBasicTableColumns: [
        // 表格初始columns
        {
          title: '品类',
          key: 'categoryPath',
          width: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 120
        }
      ],
      apiObj: {
        getProductList: {
          url: '/sysback/batch/prepare/basicinfo/getProductList', // 获取列表数据接口地址
          type: 'post' // 接口请求类型
        },
        commitBasicInfo: {
          url: '/sysback/batch/prepare/basicinfo/commitBasicInfo', // 提交接口地址
          type: 'post' // 接口请求类型
        },
        exportPageToExcelPost: {
          url: '/sysback/batch/prepare/basicinfo/exportPageToExcelPost', // 导出接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  mounted () {
    this.basicTableColumns = _.cloneDeep(this.initBasicTableColumns);
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    /* 初始化表格数据 */
    initBaseTableDataFn () {
      this.basicTableColumns = _.cloneDeep(this.initBasicTableColumns);
      this.baseTableData = [];
      this.handleDealTableTh();
      this.basicTableColumns.push({
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      });
    },
    /* 处理表头方法 */
    handleDealTableTh () {
      let dataList = this.linshiBaseTableData.reduce((value, item, index) => {
        let {
          productUuid,
          productNameFinal,
          brandName,
          categoryPath,
          spuNo,
          saleAttrInfo,
          manageArea
        } = item.main;
        value.push({
          productUuid,
          productNameFinal,
          brandName,
          categoryPath,
          spuNo,
          saleAttrInfo,
          manageArea
        });
        value[index].attrNameList = [];
        if (
          item.attrList.length === 0 ||
          item.attrList[0].officialFlag === 'N'
        ) {
          return value;
        }
        item.attrList.forEach(thItem => {
          if (thItem.attrType === '04') {
            thItem.valueName = thItem.valueName
              ? _.clone(thItem.valueName).split(/,|，|\s+/)
              : []; // 以中英文逗号、空格（一个或多个）分割字符串
          }
          value[index][thItem.attrName] = thItem;
          value[index].attrNameList.push(thItem.attrName);
          index === 0 &&
            this.basicTableColumns.push({
              title: thItem.attrName,
              align: 'center',
              key: thItem.attrName,
              type: getAttributeTypeFn(thItem.attrType),
              required: thItem.attrMust === '1' || false,
              width: thItem.attrType === '04' ? '180' : '120'
            });
        });
        return value;
      }, []);
      this.baseTableData = _.cloneDeep(dataList);
    },
    /* 关联商品 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
      this.$nextTick(() => {
        this.$refs.spuModal.getDataListAction();
      });
    },
    /* 取消对应表格row */
    handleCancelSelect (data) {
      let { row } = data;
      this.handleDeleteSpuRow(row, this.baseTableData, 'productUuid');
      this.getAssociatedGoodsAction();
    },
    /* 关联商品获取表格数据 */
    async getAssociatedGoodsAction () {
      this.linshiBaseTableData = [];
      let dataList = this.getListFromMapFn().map(value => {
        return value.uuid;
      });
      if (dataList.length === 0) {
        this.baseTableData = [];
        return false;
      }
      // let data = {
      //   productUuidList: dataList.join(','),
      // }
      let data = dataList;
      this.spuTableLoading = true;
      try {
        let res = await ApiRequest(
          `/sysback/batch/prepare/basicinfo/queryBasicInfoList`,
          'post',
          data,
          false
        );
        if (res.retStatus === '1') {
          this.linshiBaseTableData = res.retData;
        }
        this.spuTableLoading = false;
      } catch (e) {
        this.spuTableLoading = false;
      }
      this.initBaseTableDataFn();
    },
    /* 提交数据 */
    handleSubmitData () {
      if (this.baseTableData.length > ADD_BASE_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${ADD_BASE_INFO_AMOUNT}`)
      }
      let { submitResults, errorMessage } = getDealBaseDataToApiFn({
        tableData: this.baseTableData,
        type: 'add'
      });
      if (errorMessage) {
        return this.$message.warning(errorMessage);
      }
      this.submitLoading = true;
      ApiRequest(
        this.apiObj.commitBasicInfo.url,
        this.apiObj.commitBasicInfo.type,
        submitResults,
        false
      )
        .then(res => {
          this.submitLoading = false;
          if (res.retStatus === '1') {
            this.$message.success('提交成功');
            this.baseTableData = [];
            this.linshiBaseTableData = [];
            this.$router.push({ name: 'commodityNotPerfection' }); // 跳转待准入页面
          }
        })
        .catch(() => {
          this.submitLoading = false;
        });
    },
    /* 导出数据 */
    handleExportData () {
      let { submitResults } = getDealBaseDataToApiFn({
        tableData: this.baseTableData,
        type: 'add'
      });
      this.exportLoading = true;
      ApiRequestExportTable(
        this.apiObj.exportPageToExcelPost.url,
        this.apiObj.exportPageToExcelPost.type,
        submitResults,
        false
      )
        .then(res => {
          this.exportLoading = false;
          const blob = new Blob([res], { type: 'application/octet-stream' });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '批量维护基本信息.xlsx';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.exportLoading = false;
          this.$message.error('导出失败');
        });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.spuTableLoading = false;
      this.$message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.spuTableLoading = true;
      this.linshiBaseTableData = [];
      this.baseTableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (file) {
      this.spuTableLoading = false;
      if (file.retStatus === '1') {
        // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
        this.linshiBaseTableData = file.retData;
        this.initBaseTableDataFn();
      } else {
        // 如果接口返回失败,就打印失败信息
        this.$message.success(file.retMessage);
      }
    },
    /* 上传失败 */
    handleUploadError () {
      this.spuTableLoading = false;
      this.$message.error('上传失败');
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
